package com.mediacloud.app.newsmodule.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

import com.mediacloud.app.assembly.util.ConfiguRation;
import com.mediacloud.app.assembly.views.CircularImageViewX;
import android.widget.TextView;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.SubPanelData;
import com.mediacloud.app.model.news.SubUserReceiver;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.utils.SubAttentionInvoker;
import com.mediacloud.app.newsmodule.utils.SubAttentionReceiver;
import com.mediacloud.app.model.login.SubUserInvoker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yoake on 2017/7/11.
 */

public class SubPanelActivity extends Activity implements View.OnClickListener {
    private GridView mGridView;
    private TextView mChange, mOkay;
    private UserSubAdapter adapter;
    private int pageNumber = 1;
    private SubPanelData data;
    private String authorization_spider;
    private UserInfo mUser;
    private ImageView mClose;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sub_panel_layout);
        setFinishOnTouchOutside(false);
        Bundle bundle = getIntent().getBundleExtra("bundleData");
        data = (SubPanelData) bundle.getSerializable("data");
        initOther();
        initViews();

    }

    protected void initViews() {
        mGridView = findViewById(R.id.userGridView);
        adapter = new UserSubAdapter(this, data.getPageRecords());
        mGridView.setAdapter(adapter);
        mChange = findViewById(R.id.subPanelChange);
        mOkay = findViewById(R.id.subPanelOkay);
        mClose = findViewById(R.id.subColse);
        if (data.isHasNextPage() == false) {
            mChange.setTextColor(0xffAAAAAA);
            mChange.setClickable(false);
        }
        mChange.setOnClickListener(this);
        mOkay.setOnClickListener(this);
        mClose.setOnClickListener(this);
    }

    protected void initOther() {
        ConfiguRation configuRation = new ConfiguRation(SubPanelActivity.this);
        authorization_spider = configuRation.getShardString("authorization_spider", "");
        mUser = UserInfo.getUserInfo(this);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.subPanelChange) {
            getSubUserData();

        } else if (v.getId() == R.id.subPanelOkay) {
            addAttention();
        } else if (v.getId() == R.id.subColse) {
            finish();
        }
    }

    /**
     * 提交关注
     */
    protected void addAttention() {
        Map<String, SubPanelData.SubSingleData> mChooseMap = adapter.getChoosed();
        List<SubPanelData.SubSingleData> mChooseList = new ArrayList<>();
        for (String key : mChooseMap.keySet()) {
            SubPanelData.SubSingleData value = mChooseMap.get(key);
            mChooseList.add(value);
        }

        JSONArray arrays = new JSONArray();
        try {
            for (int i = 0; i < mChooseList.size(); i++) {
                JSONObject tmpObj = new JSONObject();
                tmpObj.put("userId", mChooseList.get(i).getUserId());
                tmpObj.put("userNickName", mChooseList.get(i).getUserNickName());
                if (mChooseList.get(i).getUserImage() == null || TextUtils.isEmpty(mChooseList.get(i).getUserImage())) {
                    tmpObj.put("userImage", " ");
                } else {
                    tmpObj.put("userImage", mChooseList.get(i).getUserImage());
                }
                arrays.put(tmpObj);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String arrayStr = arrays.toString();
        Log.e("", "==yoa==" + arrayStr);
        if (TextUtils.isEmpty(arrayStr)) {
            com.utils.ToastUtil.showToastCenter(SubPanelActivity.this, R.string.sub_notice_please_select, Toast.LENGTH_SHORT);
            return;
        }
        SubAttentionDataInvokeCallBack callBack = new SubAttentionDataInvokeCallBack();
        SubAttentionInvoker invoker = new SubAttentionInvoker(callBack);
        invoker.subAttention(mUser.getUserid(), mUser.getToken(), arrayStr, authorization_spider);
    }

    /**
     * 获取关注列表
     */
    protected void getSubUserData() {
        SubUserDataInvokeCallBack call = new SubUserDataInvokeCallBack();
        SubUserInvoker mSubUserInvoker = new SubUserInvoker(call);
        pageNumber++;
        mSubUserInvoker.getSubFindPage(mUser.getUserid(), mUser.getToken(), pageNumber, authorization_spider);
    }

    @Override
    public void finish() {
        ConfiguRation config = new ConfiguRation(this);
        config.shardBoolean("SUB_" + mUser.getUserid(), true);
        super.finish();
        overridePendingTransition(R.anim.in, R.anim.fade_out);
    }

    /**
     * GridView Adapter
     */
    class UserSubAdapter extends BaseAdapter {
        private Context mContext;
        private List<SubPanelData.SubSingleData> mSubs;
        private Map<String, SubPanelData.SubSingleData> mChoosed;

        public UserSubAdapter(Context mContext, List<SubPanelData.SubSingleData> mSubs) {
            this.mContext = mContext;
            this.mSubs = mSubs;
            mChoosed = new HashMap<>();
        }

        protected void setData(List<SubPanelData.SubSingleData> mSubs) {
            this.mSubs.clear();
            this.mSubs.addAll(mSubs);
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mSubs.size();
        }

        @Override
        public Object getItem(int position) {
            return mSubs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public Map<String, SubPanelData.SubSingleData> getChoosed() {
            return mChoosed;
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(mContext, R.layout.user_sub_item, null);
                holder.mUserIco = convertView.findViewById(R.id.sub_ico);
                holder.mUserName = convertView.findViewById(R.id.sub_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final SubPanelData.SubSingleData mSub = mSubs.get(position);
            holder.mUserIco.defaultBackGroundColor = 0x000000;
            holder.mUserIco.load(mSub.getUserImage());
            holder.mUserName.setText(mSub.getUserNickName());

            if (mChoosed.containsKey(mSub.getUserId() + "")) {
                holder.mUserName.setTextColor(0xffff0000);
                holder.mUserIco.setBorderColor(0xffff0000);
            } else {
                holder.mUserName.setTextColor(0xff444444);
                holder.mUserIco.setBorderColor(0x00000000);
            }

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mChoosed.containsKey(mSub.getUserId() + "")) {
                        mChoosed.remove(mSub.getUserId() + "");
                    } else {
                        mChoosed.put(mSub.getUserId() + "", mSub);
                    }
                    notifyDataSetChanged();
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        TextView mUserName;
        CircularImageViewX mUserIco;
    }

    /**
     * 数据回调
     */
    class SubUserDataInvokeCallBack implements DataInvokeCallBack<SubUserReceiver> {

        @Override
        public void success(SubUserReceiver data) {
            if (data.state == 200) {
                adapter.setData(data.data.getPageRecords());
                if (data.data.isHasNextPage() == false) {
                    mChange.setTextColor(0xffAAAAAA);
                    mChange.setClickable(false);
                }
            }
        }

        @Override
        public void fault(Object data) {
        }
    }

    class SubAttentionDataInvokeCallBack implements DataInvokeCallBack<SubAttentionReceiver> {

        @Override
        public void success(SubAttentionReceiver data) {
            if (data.success = true) {
                com.utils.ToastUtil.showToastCenter(SubPanelActivity.this, R.string.sub_success, Toast.LENGTH_SHORT);
            } else {
                com.utils.ToastUtil.showToastCenter(SubPanelActivity.this, R.string.sub_fail, Toast.LENGTH_SHORT);
            }
            finish();
        }

        @Override
        public void fault(Object data) {
            com.utils.ToastUtil.showToastCenter(SubPanelActivity.this, R.string.sub_fail, Toast.LENGTH_SHORT);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            return false;
        return super.onKeyDown(keyCode, event);
    }
}